package one.stand.zuul.controller;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import one.stand.model.ResultModel;
import one.stand.zuul.util.OneZuulException;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * 网关异常处理
 * Created by chengjiarui on 2019-06-11.
 */
@RestController
@Slf4j
public class ErrorHandlerController implements ErrorController {

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    public Object error() {
        RequestContext ctx = RequestContext.getCurrentContext();
        Throwable exception = ctx.getThrowable();
        if (Objects.nonNull(exception) && exception instanceof OneZuulException) {
            return ResultModel.fail(((OneZuulException) exception).getResultEnum());
        } else if (Objects.nonNull(exception)) {
            int status = exception instanceof ZuulException ? ((ZuulException) exception).nStatusCode : -1;
            String exceptionMessage = exception.getMessage();
            log.error("exception：{} {}", status, exceptionMessage);

            return ResultModel.fail(exceptionMessage);
        } else {
            return ResultModel.fail();
        }
    }
}
